// pages/mine/memberCentre/memberCentre.js
// import { cooperationBehavior } from "../../../behaviors/cooperation";
import api from "../../../common/api.js";
import constant from "../../../common/constant";
import {getDate} from "../../../utils/utilsNew.js";
import MD5 from "../../../utils/md5.js";
import { gioVipLog } from "../../../common/gioHandler.js";
let orderEntr, gioUser, gioMobile, gioFromId, gioCity;
var app = getApp();
var timer;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    contactWay: false,
    combo: [ ],
    comboId: 1,
    codeShow: false, //展示推广二维码的input
    toPay: false, //是否展示付款页面
    code: [], // 验证码
    focus: false, 
    srcollId: 'k0', //显示在最前面的会员套餐
    scrollLeft: 0, //判断显示的scroll到最左边的距离
    statue: 0, //会员状态
    endDate: '', //会员结束事件
    showDis: false, //是否展示折扣价
    step: 1, //支付环节
    showPushCode: 0,
    showDay: true,
    scrollLeft: '',
    selectedCoupon: 0,
    selected: 0,
    check: true,
    vipUrl: app.globalData.cdnResourceUrl + 'vip_info.png',
  },
  watch: {
    comboId: function(a, b) {
    },
  },
  openContactWay(){
    this.setData({
      contactWay: true
    })
  },
  closeContactWay(){
    this.setData({


      contactWay: false
    })
  },
  callPhone() {
    const that = this;
    wx.makePhoneCall({
      phoneNumber: "15618248836",
      success: function(res) {
      }
    })
  },
  signUp(){
    var mobile = app.globalData.sessionUser.mobile;
    let data = {
      mobile,
      activityName: '会员申请',
      activityCode: 'memberApplication',
    }
    api.addPartner(data, res => {
      if(res.data.isSuccess){
        wx.showToast({
          title: '报名成功，树懒客服将在24小时内联系您',
          duration: 2000,
          icon:'none'
        })
      }else {
        wx.showToast({
          title: '报名失败',
          icon:'none'
        })
      }
      this.setData({
        contactWay: false
      })
    })
  },
  DateAdd(interval, date){
    switch(interval){
      case 'MONTH': {
        date.setMonth(date.getMonth() + 1);
        return date;
        break;
      }
      case 'QUARTER': {
        date.setMonth(date.getMonth() + 3);
        return date;
        break;
      }
      case 'HALFYEAR': {
        date.setMonth(date.getMonth() + 6);
        return date;
        break;
      }
      case 'YEAR': {
        date.setFullYear(date.getFullYear() + 1);
        return date;
        break;
      }
    }
  },
  chooseCombo(e, b){
    // b参数代表是从优惠券跳过来的，会映射到对应的套餐和优惠券
    let that = this;
    clearInterval(timer)
    if(e&&e!='step1'&&!b){
      if(e.currentTarget.dataset.id==this.data.comboId){
        return
      }
      this.setData({
        selectedCoupon: 0,
        selected: 0,
        check: true
      })
    }
    let conboOver = new Date(this.data.startDate);
    // console.log(this.data.combo[0].packageCode)
    // let data;
    let comboId = this.data.comboId;
    if(e!='step1'&&e.currentTarget){
      // data = e!=undefined ? e.currentTarget.dataset.time:this.data.combo[0].packageCode;
      comboId =  e ? e.currentTarget.dataset.id || e.detail.value : 1;
    }
    // let conboOverTime = this.DateAdd( data , conboOver);
    // conboOverTime = conboOverTime.getTime();
    // conboOverTime = getDate('yyyy-mm-dd', conboOverTime);
    console.log(123457)
    if( this.data.combo[comboId-1].coupons&&this.data.selectedCoupon!=null){
      let endTime = this.data.combo[comboId-1].coupons[this.data.selectedCoupon].endDate;
      let timeNow = new Date().getTime();
      let lastTime = Math.ceil((endTime - timeNow)/(1000*24*60*60));
      // lastTime = lastTime>3?'':lastTime;
      if(lastTime<2){
        clearInterval(timer)
        timer = setInterval(() => {
          lastTime = that.getDuration(endTime - new Date().getTime())
          that.setData({
            lastTime
          })
        }, 1000);
      }else {
        that.setData({
          lastTime: ''
        })
        clearInterval(timer)
      }
      this.setData({
        haveTime: lastTime,
        comboId,
        // conboOverTime,
      })
    }else {
      this.setData({
        comboId,
        // conboOverTime,
      })
    }
  },
  // ssss(){
  //   let updata = {};
  //   updata.type = this.data.combo[this.data.comboId-1].packageCode;
  //   updata.selectedCoupon = 0
  //   this.onLoad(updata)
  // },
  getDuration(time) {
    let days = parseInt(time / (1000 * 60 * 60 * 24));
        let hours = parseInt(time % (1000 * 60 * 60 * 24) / (1000 * 60 * 60));
        let minutes = parseInt(time % (1000 * 60 * 60) / (1000 * 60));
        let seconds = parseInt(time % (1000 * 60) / 1000);
        // 格式 00天 00时 00分 00秒
        if (days < 10) { 
            days = '0' + days
        }
        if (hours < 10) {
            hours = '0' + hours
        }
        if (minutes < 10) {
            minutes = '0' + minutes
        }
        if (seconds < 10) {
            seconds = '0' + seconds
        }
        return hours + ":" + minutes + ":" + seconds;
  },
  showCode(){
    this.setData({
      codeShow: true,
      focus: true,
    })
  },
  closePay(){
    this.setData({
      toPay: false,
      codeShow: false,
      focus: false,
      code: [],
    })
  },
  openPay(){
    this.setData({
      toPay: true,
    })
  },
  click(){
  },
  input(e){
    let that=this
    let arr=[]
    for(let i=0;i<e.detail.value.length;i++){
    arr.push(e.detail.value[i])
      if(i==3){
        this.setData({
          codeValue:e.detail.value,
        })
        // this.getInfoByPushCode(e.detail.value);
        // wx.hideKeyboard()
      }
    }
    that.setData({
    code:arr
    })
  },
  getFoucs(){
    let that=this
    that.setData({
      focus:true
    })
  },
  blur(){
    let that=this
    that.setData({
      focus:false
    })
  },
  moveEnd(e){
    // console.log('结束',e)
  },
  moveStart(e){
    // console.log('开始',e)
  },
  getMemberList(){
    return new Promise((resolve, reject) => {
      let memberAgentId = getApp().globalData.loginUserInfo.data.content.sessionUser.id;
      api.getMemberList({
        "currentPage": 1,
        "pageSize": 1,
        "t": {
          "memberAgentId": memberAgentId
        }
      },(res)=>{
        resolve(res)
      })
    })
  },
  // 支付
  payfor(e){
    if(e.currentTarget.dataset.style){
      gioVipLog(constant.Click_Pay, gioFromId, orderEntr)
    }
    let that = this;
    let pushCode = this.data.combo[this.data.comboId-1].newPrice?that.data.codeValue:(this.data.combo[this.data.comboId-1].coupons&&this.data.selectedCoupon!=null?this.data.combo[this.data.comboId-1].coupons[this.data.selectedCoupon].id:null)
    api.onlinePayment({
      pushCode,
      cardType: this.data.combo[this.data.comboId-1].packageCode,
    },res=>{
      const timeStamp = String(new Date().getTime());
      const nonceStr = res.data.content.nonceStr;
      const rpackage = "prepay_id="+res.data.content.prepayId;
      let afterMemberDate = res.data.content.endDate;
      var newSign = "appId=wx588145c78e18fa1b&nonceStr=" + nonceStr + "&package=" + rpackage + "&signType=MD5&timeStamp=" + timeStamp +"&key=9233337b7c499e6bbf5d68f380dd94e4";
      const rpaySign = MD5.hex_md5(newSign)
      wx.requestPayment({
        nonceStr: nonceStr,
        package: rpackage,
        paySign: rpaySign,
        timeStamp: timeStamp,
        signType: 'MD5',
        success(res) {
          wx.reLaunch({
            url: '/pages/mine/paySuccess/paySuccess?orderType='+that.data.combo[that.data.comboId-1].packageCode+'&startData='+that.data.startDate+'&type='+that.data.combo[that.data.comboId-1].packageName+'&endDate='+afterMemberDate,
          })
        },
        fail(res) {
          wx.showToast({
            title:'请求支付失败，请稍后重试',
            icon: 'none',
            duration: 2000
          })
        }
      })
    })
  },
  // 帐号被禁止
  banPay(){
    wx.showToast({
      title:'您的帐号已被禁用，请联系客服！',
      icon: 'none',
      duration: 2000
    })
  },
  // 查询折扣
  getInfoByPushCode(){
    let that = this;
    return new Promise((resolve, reject) => {
      let pushData = {
        pushCode: this.data.codeValue
        // pushCode: '1664'
      }
      api.getInfoByPushCode((pushData),res => {
        try {
          // 如果没有返回新价格代表验证码无效
          if(!res.data.content[0].newPrice){
            this.confirmCode();
            return
          }else {
            this.setData({
              showPushCode: 0
            })
          }
          let content = res.data.content;
          let combo1 = that.data.combo;
          combo1.map( n => {
            content.map( p => {
              if(n.packageCode==p.packageCode){
                n.endDate = getDate('yyyy-mm-dd', p.endDate);
                n.startDate = getDate('yyyy-mm-dd', p.startDate);
              }
            })
          })
          that.setData({
            combo: combo1,
          })
          if(res.data.content[0].newPrice){
            combo1.map( n => {
              content.map( p => {
                if(n.packageCode==p.packageCode){
                  n.newPrice = (p.newPrice).toFixed(2);
                  n.activityDay = p.activityDay;
                }
              })
            })
            this.setData({
              combo: combo1,
              showDis: true,
            })
          }else {
            this.setData({
              showDis: false,
            })
          }
          
        } catch (error) {
          
        }

      })  
    })
  },
  getSessionInfo(){
    return new Promise((resolve, reject) => {
      let that = this;
      api.getSessionInfo(null, function (res) {
        let data = res.data.content;
        that.setData({
          img: data.avatar,
          name: data.realName == null ? data.username : data.realName,
        })
        resolve();
      })
    })
  },
  openCodeWindw(){
    this.setData({
      showPushCode: 1
    })
  },
  closeCodeWindow(){
    this.setData({
      showPushCode: 0
    })
  },
  newPushCode(){
    this.setData({
      showPushCode: 1,
      code: [],
      codeValue: null
    })
  },
  confirmCode(){
    this.setData({
      showPushCode: 2,
    })
  },
  goStep1(){
    this.chooseCombo('step1')
    this.setData({
      step: 1
    })
  },
  goStep2(){
    this.setData({
      step: 2
    })
  },
  goStep3(){
    this.setData({
      step: 3
    })
  },
  confirmUse(){
    let combo = this.data.combo[this.data.comboId-1].coupons;

    // 判断是否有选择优惠券
    let bool = false;
    combo.map(v => {
      if(v.checked){
        bool = true
      }
    })
    this.setData({
      selectedCoupon: this.data.check||!this.data.check&&bool?this.data.selected:null,
      step: 2
    })
  },
  radioChange(e){
    console.log('radio发生change事件，携带value值为：', e)
    let combo = this.data.combo;
    combo.map(v=>{
      if(v.coupons){
        v.coupons.map(n=>{
          n.checked=false
        })
      }
    })
    // console.log()
    this.setData({
      check: true,
      selected: e.detail.value,
      combo
    })
  },
  formatDateTime(timeStamp){
    var date = new Date(timeStamp);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    //day 有值-返回带分秒的
      return y + '.' + m + '.' + d
  }, 
  checkedTap(e){
    // if(e.currentTarget.dataset.index != this.data.selected){
    //   return
    // }
    let combo = this.data.combo;
    combo[this.data.comboId-1].coupons[this.data.selected].checked=!combo[this.data.comboId-1].coupons[this.data.selected].checked;
    let selected = this.data.selected;
    this.setData({
      combo,
      // check: combo[this.data.comboId-1].coupons[this.data.selected].checked
      check: false,
      // selected: this.data.selected==null?selected:null
    })
  },
  // handdleMove(){
  //   return
  // },
  // 选择套餐
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options, 12345)
    app.globalData.loginPromise.then(()=>{
      app.mobileLogin(null, '树懒超级会员', false)
      .then(() => {
      })
      .catch(() => {
        app.globalData.afterMobileAuthorCallBack = () => {
          wx.redirectTo({ url: "/pages/mine/memberCentre/memberCentre" })
        }
      })
      orderEntr = options.orderEntr||'';
      gioUser = wx.getStorageSync('user')
      gioMobile = app.globalData.sessionUser.extProps.wxMobile||app.globalData.sessionUser.mobile
      gioFromId = wx.getStorageSync('fromUserId')
      gioCity = wx.getStorageSync('currentCity')

      gioVipLog(constant.View_Pur_Chase, gioFromId, orderEntr)

      this.getMemberList().then((res)=>{
        let content = res.data.content;
          this.getSessionInfo().then(()=> {
            let img = this.data.img;
            let name = this.data.name;
            if(content.statue==0){
              let endDate = getDate('yyyy/mm/dd', content.endDate);
              endDate = endDate.replace(/(\/)/g,'-');
              let startDate = new Date(endDate);
              startDate = startDate.setDate(startDate.getDate()+1);
              // console.log(startDate,'结束时间')
              let endDay = startDate;
              // console.log(endDay,'结束时间')
              let now = new Date().getTime();
              // console.log(now,'现在时间')
              let lastDay = ((endDay - now)/(24*60*60*1000));
              lastDay = Math.floor(lastDay)
              // console.log(lastDay,'剩余时间')
              startDate = getDate('yyyy-mm-dd', startDate);
              this.setData({
                statue: content.statue,
                endDate: endDate,
                startDate: startDate,
                lastDay,
                img: img,
                name: name,
              })
            }else if(content.statue==1){
              this.setData({
                statue: content.statue,
                img: img,
                name: name,
              })
            }else if(content.statue==2||content.statue==3){
              let today = getDate('yyyy-mm-dd', (new Date()).getTime());
              this.setData({
                statue: content.statue,
                startDate: today,
                endDate: today,
                img: img,
                name: name,
              })
            }
            api.getMembershipCard({}, res => {
              let combo = [];
              
              try {
                res.data.content.map((v, index) => {
                  v.comboId = index+1
                  if(v.packageStatue == 0){
                    combo.push(v)
                  }
                })
              } catch (error) {
                
              }

              api.getMyCoupons({
                activityCode: 'MEMBERFISSION'
              }, res => {
                try {
                  let getMyCoupons = res.data.content;
                  combo.map(v => {
                    getMyCoupons.map(f=>{
                      if(v.packageCode==f.packageCode){
                        v.couponAmount = f.couponAmount;
                        v.fissionPrice = f.newPrice;
                        v.couponId = f.couponId;
                      }
                    })
                  })
                } catch (error) {
                  
                }
        
                api.getMyMemberCouponsInfo({}, res => {
                  let couponsInfo = res.data.content;
                  if (!couponsInfo) return

                  combo.map(v=>{
                    if(couponsInfo[v.packageCode].length){
                      v.coupons = couponsInfo[v.packageCode]
                    }
                    if(v.coupons){
                      v.coupons.map(n => {
                        n.couponContent = JSON.parse(n.couponContent)
                        n.checked= false
                        let l = n.cardType.split(',').length - 1;
                        if(l==3){
                          n.canUseTypeText = '购买任意会员均适用'
                        }else {
                          n.canUseTypeText = '购买'+n.cardType.replace('HALFYEAR','半年卡').replace('YEAR','年卡').replace('QUARTER','季卡').replace('MONTH','月卡')+'会员适用'
                        }
                        n.startTime = this.formatDateTime(n.startDate)
                        n.endTime = this.formatDateTime(n.endDate)
                      })
                    }
                  })


                  this.setData({
                    combo
                  })
                  if(options.type){
                    let couponType = options.type;
                    let couponId = options.couponId;
                    let selectedCoupon = options.selectedCoupon;
                    let combo = this.data.combo;
                    combo.map((v, index) => {
                      if(v.packageCode==couponType){
                        // this.rolldistance()
                        this.setData({
                          comboId: index+1,
                          selectedCoupon
                        })
                        combo[this.data.comboId-1].coupons[selectedCoupon].checked = true
                        this.setData({
                          combo,
                          selected: selectedCoupon
                        })
                        this.chooseCombo(this.data.comboId, selectedCoupon)
                        setTimeout(()=>{
                          this.setData({
                            scrollLeft: index*170
                          })
                        }, 100)
                      }
                    })
                  }
                })
              })
            })    
          })
      })  
    })
    // })
  },

})